<?php

require_once realpath(dirname(__FILE__) . '//..//pages.php');
require_once INC_FUNCTIONS;
require_once MDL_ACTIONS;
require_once MDL_TABLES;

function getModels() {
    return $profiles = array(
        'admin' => array(
            'delete' => array('all'),
            'edit' => array('all'),
            'insert' => array('all'),
            'view' => array('all')
        ),
        'deleter' => array(
            'delete' => array('all')
        ),
        'editor' => array(
            'edit' => array('all')
        ),
        'supervisor' => array(
            'supervise' => array('all')
        )
    );
}

function generatePermissions($delete_old = false) {
    $actions = array_keys(getActions());
    $tables = array_keys(getTables());
    $stats = array_keys(getStats());
    $db = openConnection(true);

    if ($delete_old) {
        $db->delete('permesso');
    }

    foreach ($actions as $action) {
        if ($action == 'supervise') {
            foreach ($stats as $stat) {
                if ($db->insert('permesso', array('action' => $action, 'what' => $stat), true)) {
                    echo '...Successful!<br>';
                } else {
                    echo '...Failed!<br>';
                }
            }
        }
        foreach ($tables as $table) {
            if ($db->insert('permesso', array('action' => $action, 'what' => $table), true)) {
                echo '...Successful!<br>';
            } else {
                echo '...Failed!<br>';
            }
        }
    }
    echo '<a href="javascript:history.back();">Torna alla pagina precedente</a>';
}

function assign($model, $IDuser) {
    $db = openConnection(true);
    $profiles = getModels();
    foreach ($profiles[$model] as $action => $tables) {
        $where = "permesso.action='$action'";
        $AND = true;
        foreach ($tables as $table) {
            if ($table == 'all') {
                break;
            } else {
                if ($AND) {
                    $AND = false;
                    $where .= ' AND (';
                }
                $where .= "permesso.what='$table' OR ";
            }
        }
        if (!$AND) {
            $where = substr($where, 0, strlen($where) - 3);
            $where .= ')';
        }
        $result = $db->select('permesso', 'ID', $where);
        while ($row = $db->fetchAssoc($result)) {
            $db->insert('possiede', array('IDuser' => $IDuser, 'IDpermesso' => $row['ID']));
        }
    }
    echo '<a href="javascript:history.back();">Torna alla pagina precedente</a>';
}

?>
